<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    th,
    td {
      border: 1px solid #ddd;
      padding: 8px;
    }

    th {
      position: sticky;
      top: 0;
      z-index: 1;
      background-color: #f2f2f2;
    }

    .footer {
      width: 100%;
      height: 50px;
      background: linear-gradient(to right, #f0ecf4, #b5c2d7);
      display: flex;
      align-items: center;
      justify-content: center;
      position: fixed;
      bottom: 0;
      z-index: 2;
    }

    body {
      padding-bottom: 70px;
      /* 确保内容不会被底部栏遮挡 */
    }

    .pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    .pagination button,
    .pagination input {
      margin: 0 5px;
      padding: 5px 10px;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      background-color: #fff;
      color: #606266;
      outline: none;
    }

    .pagination button:hover {
      color: #409eff;
    }

    .pagination button.active {
      background-color: #409eff;
      color: #fff;
    }

    .pagination input {
      width: 50px;
      text-align: center;
    }
  </style>
</head>

<body>
  <div
    style="display: flex;flex-direction: row;justify-content: space-evenly;align-items: center;background:linear-gradient(to right, #f0ecf4, #b5c2d7)">
    <h1
      style="font-size: 20px;font-weight: normal;border: 1px solid blue;background-color: rgb(130, 130, 234);padding: 15px;">
      信息回传界面</h1>
  </div>
  <table id="data-table">
    <thead>
      <tr>
        <th>序号</th>
        <th>运单号</th>
        <th>重量（kg）</th>
        <th>长度（mm）</th>
        <th>宽度（mm）</th>
        <th>高度（mm）</th>
        <th>体积（m³）</th>
        <th>扫描时间</th>
        <th>状态</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>

  <div class="pagination" id="pagination">
    <!-- 页码按钮将在这里动态生成 -->
  </div>

  <div class="search-container" style="text-align: center; margin-top: 30px;">
    <input type="text" id="search-input" placeholder="输入运单号"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; outline: none;">
    <button id="search-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">查询</button>
  </div>
  <div style="display: flex;flex-direction: column;">
    <div>
      <button id="switch-button"
        style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #573333; color: #e7ebf3; cursor: pointer; outline: none;">切换上传</button>
      <h3 style="display: inline-block;">当前为：<h3 style="display: inline-block;" id="switchMode">Loading...</h3>
      </h3>
    </div>
    <div>
      <button id="waveWeight-button"
        style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #573333; color: #e7ebf3; cursor: pointer; outline: none;">切换称重模式</button>

      <h3 style="display: inline-block;">
        <h3 style="display: inline-block;" id="waveWeight">Loading...</h3>
      </h3>
    </div>
  </div>
  <div class="results-container" id="results-container">
    <!-- 查询结果将显示在这里 -->
  </div>

  <div class="datetime-container" style="text-align: center; margin-top: 30px;">
    <label for="start-time">开始时间:</label>
    <input type="datetime-local" id="start-time"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; outline: none;">
    <label for="end-time">结束时间:</label>
    <input type="datetime-local" id="end-time"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; outline: none;">
    <button id="export-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">导出</button>
  </div>

  <script>
    let ws;
    let currentPage = 1;
    let totalPages = 1;
    const limit = 10; // 每页显示的记录数
    let showData = false
    function startWebSocket() {
      ws = new WebSocket('ws://127.0.0.1:3000');

      ws.onopen = () => {
        console.log('WebSocket connection established');
      };

      ws.onmessage = (event) => {
        if (event.data === 'ping') {
          ws.send(JSON.stringify({ info: 'pong' }));
          return;
        }
        if (event.data === 'logMessage') {
          fetchLogs(currentPage)
        }
      };

      ws.onclose = () => {
        console.log('WebSocket connection closed');
        setTimeout(startWebSocket, 2000);
      };

      ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        setTimeout(startWebSocket, 2000);
      };
    }

    function fetchLogs(page) {
      fetch(`http://localhost:3001/logs?page=${page}&limit=${limit}`)
        .then(response => response.json())
        .then(data => {
          showData = data.results.some(log => log.mapData.length !== undefined && log.mapData.length !== null && log.mapData.length !== ''); // 检查是否有记录包含体积数据
          renderTable(data.results);
          totalPages = Math.ceil(data.total / limit);
          createPagination();
        })
        .catch(error => console.error('Error fetching logs:', error));
    }

    function renderTable(logs) {
      const tableBody = document.querySelector('#data-table tbody');
      tableBody.innerHTML = '';

      const tableHead = document.querySelector('#data-table thead tr');
      if (showData) {
        tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>长度（mm）</th>
      <th>宽度（mm）</th>
      <th>高度（mm）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
      } else {
        tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
      }

      logs.forEach((log, index) => {
        const row = document.createElement('tr');
        if (showData) {
          row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${log.mapData.code}</td>
        <td>${log.mapData.weight}</td>
        <td>${log.mapData.length}</td>
        <td>${log.mapData.width}</td>
        <td>${log.mapData.height}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
        } else {
          row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${log.mapData.code}</td>
        <td>${log.mapData.weight}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
        }

        tableBody.appendChild(row);
      });
    }

    function createPagination() {
      const pagination = document.getElementById('pagination');
      pagination.innerHTML = '';

      const maxVisiblePages = 3; // 最多显示的页码数
      const halfMaxVisiblePages = Math.floor(maxVisiblePages / 2);

      let startPage = Math.max(1, currentPage - halfMaxVisiblePages);
      let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
      startPage = Math.max(1, endPage - maxVisiblePages + 1);

      for (let i = startPage; i <= endPage; i++) {
        const button = document.createElement('button');
        button.textContent = i;
        button.classList.add('page-button');
        if (i === currentPage) {
          button.classList.add('active');
        }
        button.addEventListener('click', () => {
          currentPage = i;
          fetchLogs(currentPage);
        });
        pagination.appendChild(button);
      }

      if (startPage > 1) {
        const ellipsis = document.createElement('span');
        ellipsis.textContent = '...';
        pagination.insertBefore(ellipsis, pagination.firstChild);
      }

      if (endPage < totalPages) {
        const ellipsis = document.createElement('span');
        ellipsis.textContent = '...';
        pagination.appendChild(ellipsis);
      }

      const gotoInput = document.createElement('input');
      gotoInput.type = 'number';
      gotoInput.min = 1;
      gotoInput.max = totalPages;
      gotoInput.placeholder = 'Go to';
      gotoInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
          const gotoPage = parseInt(gotoInput.value, 10);
          if (!isNaN(gotoPage) && gotoPage >= 1 && gotoPage <= totalPages) {
            currentPage = gotoPage;
            fetchLogs(currentPage);
          }
        }
      });
      pagination.appendChild(gotoInput);
    }

    function displayResults(logs) {
      const resultsContainer = document.getElementById('results-container');
      resultsContainer.innerHTML = ''; // 清空之前的查询结果

      if (logs.length === 0) {
        resultsContainer.innerHTML = '<h2>没有找到匹配的日志</h2>';
        return;
      }

      const ul = document.createElement('ul');
      logs.forEach(log => {
        const li = document.createElement('li');
        li.innerHTML = `
                    <strong>运单号:</strong> ${log.mapData.code}<br>
                    <strong>响应:</strong> ${log.response}<br>
                    <strong>时间:</strong> ${log.formattedTime}
                `;
        ul.appendChild(li);
      });

      resultsContainer.appendChild(ul);
    }

    startWebSocket();
    fetchLogs(currentPage); // 初始加载第一页数据

    document.getElementById('search-button').addEventListener('click', () => {
      const searchCode = document.getElementById('search-input').value.trim();
      if (searchCode) {
        fetch(`http://localhost:3001/logs/selectLog?code=${searchCode}`)
          .then(response => response.json())
          .then(data => {
            displayResults(data.logs);
          })
          .catch(error => console.error('Error fetching logs:', error));
      } else {
        alert('请输入运单号');
      }
    });

    document.getElementById('switch-button').addEventListener('click', () => {
      fetch('http://localhost:3001/gwWCS/switchMode')
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
          }
          return response.json(); // 解析JSON数据
        })
        .then(data => {
          // 提取 data 对象的值
          const message = data.data.message;
          const isSwitch = data.data.isSwitch;
          // 在这里处理提取的值，例如更新UI
          // console.log('Message:', message);
          // console.log('isSwitch:', isSwitch);
          alert(data.data.message)
          if (isSwitch === 1) {
            // 更新UI，显示当前模式为1
            document.getElementById('switchMode').innerText = '上传模式';
          } else if (isSwitch === 2) {
            // 更新UI，显示当前模式为2
            document.getElementById('switchMode').innerText = '不上传模式';
          }
        })
        .catch(error => {
          console.error('Error fetching switch mode:', error);
        });
    });

    document.getElementById('waveWeight-button').addEventListener('click', () => {
      fetch('http://localhost:3001/gwWCS/switchWaveWeight')
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
          }
          return response.json(); // 解析JSON数据
        })
        .then(data => {
          // 提取 data 对象的值
          const message = data.data.message;
          const isWaveWeight = data.data.isWaveWeight;
          // 在这里处理提取的值，例如更新UI
          // console.log('Message:', message);
          // console.log('isSwitch:', isSwitch);
          alert(data.data.message)
          if (isWaveWeight == 1) {
            // 更新UI，显示当前模式为1
            document.getElementById('waveWeight').innerText = '批量（波次为维度）';
          } else if (isWaveWeight == 0) {
            // 更新UI，显示当前模式为0
            document.getElementById('waveWeight').innerText = '单个称重';
          }
        })
        .catch(error => {
          console.error('Error fetching switch mode:', error);
        });
    });

    document.getElementById('export-button').addEventListener('click', () => {
      const startTime = document.getElementById('start-time').value;
      const endTime = document.getElementById('end-time').value;
      if (startTime && endTime) {
        const formattedStartTime = new Date(startTime).toISOString().replace('T', ' ').slice(0, 19);
        const formattedEndTime = new Date(endTime).toISOString().replace('T', ' ').slice(0, 19);
        fetch(`http://localhost:3001/gwWCS/logs/selectSwitchLog?startTime=${formattedStartTime}&endTime=${formattedEndTime}`)
          .then(response => response.json())
          .then(data => {
            // 自定义表头
            const headers = [
              { header: 'ID', key: 'id' },
              { header: '单号', key: 'code' },
              { header: '重量', key: 'weight' },
              { header: '长', key: 'length' },
              { header: '宽', key: 'width' },
              { header: '高', key: 'height' },
              { header: '时间', key: 'formattedTime' }
            ];

            // 转换数据格式
            const formattedData = data.logs.map((log, index) => ({
              id: index,
              code: log.mapData.code,
              weight: log.mapData.weight,
              length: log.mapData.length,
              width: log.mapData.width,
              height: log.mapData.height,
              formattedTime: log.formattedTime
            }));

            // 生成 Excel 文件
            const ws = XLSX.utils.json_to_sheet(formattedData, { header: headers.map(h => h.key) });
            XLSX.utils.sheet_add_aoa(ws, [headers.map(h => h.header)], { origin: 'A1' });
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Logs");
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

            // 下载 Excel 文件
            saveAs(new Blob([wbout], { type: "application/octet-stream" }), "logs.xlsx");

            alert('数据已导出');
            console.log('Export data:', data);
          })
          .catch(error => console.error('Error exporting logs:', error));
      } else {
        alert('请选择开始时间和结束时间');
      }
    });

    document.addEventListener('DOMContentLoaded', function () {
      fetch('http://localhost:3001/gwWCS/getSwitchMode')
        .then(response => response.text())
        .then(data => {
          data = JSON.parse(data)
          if (data.isSwitch === 1) {
            document.getElementById('switchMode').innerText = '上传模式';
          } else {
            document.getElementById('switchMode').innerText = '非上传模式';
          }
          if (data.waveWeight == 1) {
            document.getElementById('waveWeight').innerText = '批量（波次为维度）';
          } else {
            document.getElementById('waveWeight').innerText = '单个称重';
          }
        })
        .catch(error => {
          console.error('Error fetching switch mode:', error);
        });
    });
  </script>
  <div class="footer">
    <div class="foo_main">&copy; 版权所有 </div>
  </div>
</body>

</html>